﻿using Api.Bll;
using Api.Dal;
using Api.Model;
using Api.Dal.Tools;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using System.Data;
using Microsoft.AspNetCore.Cors;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [EnableCors("_myAllowSpecificOrigins")]
    public class UserController : ControllerBase
    {

        [HttpGet]
        //[HttpGet]
       //url = user时用于登录
        public string GetLoginuser(
            string name,
            string password)
        {
            IPeople people;
            try
            {
                people = PeopleFactory.getPeople(name, password);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            return JsonConvert.SerializeObject(people); 
        }
        //url = user/id时用于查找用户
        [HttpGet("{id}")]
        public string GetUser(int id)
        {
            User user = new User();
            user.id = id;
            User? u = BllFactory.GetUserBLL().GetUser(user);
            if (u == null)
                return "None";
            string userJson = JsonConvert.SerializeObject(u);
            return userJson;
        }

        [HttpPost]
        public string InsertUser(User u)
        {
            if (Checkpw.IsPasswordSecure(u.password) == false) return "-1";
            User user = new User();
            user.name = u.name;
            user.password = u.password;
            return BllFactory.GetUserBLL().InsertUser(user);
        }

        [HttpPut]
        public bool UpdateUser(string userJson)
        {
            User? u = JsonConvert.DeserializeObject<User>(userJson);
            if(u == null) return false;
            return BllFactory.GetUserBLL().UpdateUser(u);
        }
        [HttpDelete]
        public bool MyDelete(int uid)
        {
            return BllFactory.GetUserBLL().DeleteUser(uid);
        }

        [HttpPost("changeIcon")]
        public bool changeIcon(int userId,string path)
        {
            return BllFactory.GetUserBLL().changeIcon(userId,path);
        }
    }
}
